package com.cn.xiaonuo.slbfinances.slborders.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cn.xiaonuo.common.constant.OrderPaymentChannel;
import com.cn.xiaonuo.common.entity.BusinessMessage;
import com.cn.xiaonuo.common.tools.RestTemplateUtil;
import com.cn.xiaonuo.dbs.core.annotation.DataSource;
import com.cn.xiaonuo.slbfinances.slborders.entity.CommonOrder;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlOrder;
import com.cn.xiaonuo.slbfinances.slborders.entity.SlOrderRefund;
import com.cn.xiaonuo.slbfinances.slborders.mapper.CmOrderMapper;
import com.cn.xiaonuo.slbfinances.slborders.mapper.CmOrderRefundMapper;
import com.cn.xiaonuo.slbfinances.slborders.param.CommonOrderParam;
import com.cn.xiaonuo.slbfinances.slborders.param.RefundReqParam;
import com.cn.xiaonuo.slbfinances.slborders.service.ICoverageOrderRefundService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
@Service
@Slf4j
public class CoverageOrderRefundServiceImpl extends ServiceImpl<CmOrderRefundMapper, SlOrderRefund> implements ICoverageOrderRefundService {
    @Resource
    private CmOrderRefundMapper cmOrderRefundMapper;
    @Resource
    private Environment environment;
    @Autowired
    private RestTemplateUtil restTemplateUtil;
    @Resource
    private CmOrderMapper cmOrderMapper;

    @Override
    /*财务退款后台查询*/
    @DataSource(name = "jyb_soole_data_hn")
    public BusinessMessage selectFinanceRefund(CommonOrderParam slbOrderReqParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = slbOrderReqParam.getPageSize();
            Integer pageNo = slbOrderReqParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            CommonOrder commonOrder=new CommonOrder();
            BeanUtil.copyProperties(slbOrderReqParam,commonOrder);
            PageHelper.startPage(pageNo,pageSize);
            List<Map<String, Object>> mapList = cmOrderRefundMapper.selectFinanceRefund(commonOrder);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            message.setCode("200");
            message.setData(pageInfo);
            message.setMessage("操作成功");
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode("-1");
            message.setMessage("操作失败");
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }
    /**
     *
     * @param slbOrderReqParam
     * @return
     */
    @DataSource(name = "jyb_soole_data_hn")
    @Override
    public BusinessMessage applyFinanceRefund(CommonOrderParam slbOrderReqParam) {
        BusinessMessage message = new BusinessMessage();
        try {
            Integer pageSize = slbOrderReqParam.getPageSize();
            Integer pageNo = slbOrderReqParam.getPageNo();
            if (null == pageNo || Integer.valueOf(pageNo) <= 1) {
                pageNo = 1;
            }
            if (null == pageSize || Integer.valueOf(pageSize) <= 1) {
                pageSize = 10;
            }
            CommonOrder commonOrder = new CommonOrder();
            BeanUtil.copyProperties(slbOrderReqParam, commonOrder);
            PageHelper.startPage(pageNo, pageSize);
            List<Map<String, Object>> mapList = cmOrderRefundMapper.applyFinanceRefund(commonOrder);
            PageInfo<Map<String, Object>> pageInfo = new PageInfo<>(mapList);
            message.setCode("200");
            message.setData(pageInfo);
            message.setMessage("操作成功");
            message.setSuccess(true);
        } catch (Exception e) {
            message.setCode("-1");
            message.setMessage("操作失败");
            message.setSuccess(false);
            e.printStackTrace();
        }
        return message;
    }

    /**
     * 打款
     */
/*    @DataSource(name = "jyb_soole_data_hn")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public BusinessMessage updateFinanceState(RefundReqParam param) {
        BusinessMessage message = new BusinessMessage();
        try {
            String localTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            SlOrderRefund orderRefund = cmOrderRefundMapper.selectById(param.getId());
            if (null != orderRefund.getOrderId()) {
                String url = environment.getProperty("gwq.gwqUrl");
                String method = environment.getProperty("gwq.refund");
                String token = environment.getProperty("gwq.token");
                param.setBillNo("89844016051000320221118340861952");
                param.setReceiverMerchantNo("PS_51876384745717760");
                param.setReceiverType(0);
                param.setRefundAmount(2L);
                String json = JSON.toJSONString(param);
                log.info("搜了宝远程调用分账打款功能开始：参数{}",json);
                Map data = restTemplateUtil.post(url, method, json,token);
                log.info("搜了宝远程调用分账打款功能成功：{}", data);
                //修改打款状态
                cmOrderRefundMapper.updateFinanceState(param.getId(), param.getUserId(), localTime, param.getActmoney());
                //修改订单明细为：7退款成功
                cmOrderRefundMapper.updateOrderDetailShipState(orderRefund.getOrderId(), localTime);
                //修改订单支付状态为:102申请售后
                cmOrderRefundMapper.updateOrderPaymentState(orderRefund.getOrderId());
            } else {
                message.setCode("-1");
                message.setMessage("订单不存在!");
                message.setSuccess(false);
            }
            message.setCode("200");
            message.setMessage("操作成功");
            message.setSuccess(true);
        }catch (Exception e){
            message.setCode("-1");
            message.setMessage("操作失败");
            message.setSuccess(false);
            log.info("搜了宝远程调用分账打款功能异常：{}", e.getMessage());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
        }
        return message;
    }*/
    @Value("${jyb.jybPay.refundByOrderNumber}")
    private String jybRefundUrl;
    @Resource
    private RestTemplate restTemplate;
    /**
     * 打款
     *
     * @param id
     * @param userId
     * @param actmoney
     * @return
     */
    @DataSource(name = "jyb_soole_data_hn")
    @Transactional(rollbackFor = Exception.class)
    @Override
    public BusinessMessage updateFinanceState(Integer id, String userId, String actmoney) {
        BusinessMessage message = new BusinessMessage();
        message.setCode("200");
        message.setMessage("操作成功");
        message.setSuccess(true);
        String localTime = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        SlOrderRefund orderRefund = cmOrderRefundMapper.selectById(id);
        if(orderRefund.getFinanceCheckState() == 1){
            message.setCode("-1");
            message.setMessage("该退款已审核，请勿重复退款！");
            message.setSuccess(false);
            return message;
        }
        if (null != orderRefund.getOrderId()) {
            //修改打款状态
            cmOrderRefundMapper.updateFinanceState(id, userId, localTime, actmoney);
            //修改订单明细为：7退款成功
            cmOrderRefundMapper.updateOrderDetailShipState(orderRefund.getOrderId(), localTime);
            //修改订单支付状态为:102申请售后
            cmOrderRefundMapper.updateOrderPaymentState(orderRefund.getOrderId());
            // 支付类型为货款直接修改交易中心货款
            SlOrder slOrder = cmOrderMapper.selectById(orderRefund.getOrderId());
            if(slOrder.getPaymentChannel() == OrderPaymentChannel.paymentForGoods){
                String orderNumber = slOrder.getOrderNumber();
                String url = jybRefundUrl+"?orderNumber="+orderNumber;
                String s = restTemplate.postForObject(url, null, String.class);
                JSONObject jsonObject = JSON.parseObject(s);
                if(!jsonObject.getBoolean("success")){
                    TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    message.setCode("-1");
                    message.setMessage(jsonObject.getString("message"));
                    message.setSuccess(false);
                }
            }
        } else {
            message.setCode("-1");
            message.setMessage("操作失败");
            message.setSuccess(false);
        }
        return message;

    }
}
